<template>
  <a-modal 
    :visible="passwordDialog" 
    title="修改密码"
    okText="确认修改"
    cancelText="放弃更改"
    :maskClosable=false
    @ok="controlSwitch(true)"
    @cancel="controlSwitch(false)">
      <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 15 }" @submit="handleSubmit">
        <a-form-item 
          v-for="(item, index) in passwordForm"
          :key="index"
          :label="item.label">
          <a-input-password
            v-decorator="[item.prop, {rules: item.rules}]"
          />
        </a-form-item>
      </a-form>
    </a-modal>
</template>

<script>
import {updatePassword} from '@/api/linYi'
import {message} from "ant-design-vue"
export default {
  props: {
    passwordDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: this.$form.createForm(this, { name: 'coordinated' }),
      passwordForm: [
        {
          label: '旧密码',
          prop: 'oldPassword',
          rules: [
            { required: true, message: '请输入旧密码' }
          ]
        },
        {
          label: '新密码',
          prop: 'password',
          rules: [
            { required: true, message: '请输入新密码' },
          ]
        },
        {
          label: '再次确认',
          prop: 'truePassword',
          rules: [
            { required: true, message: '请再次输入' },
            { validator: this.confirmPassword }
          ]
        }
      ]
    }
  },
  methods: {
    confirmPassword(rule, value, callback) {
      return value === this.form.getFieldValue('password')? callback() : callback('两次新密码输入不一致')
    },
    controlSwitch(sign) {
      sign? this.handleSubmit() : this.$emit("defaultPasswordDialog")
    },
    handleSubmit() {
      this.form.validateFields((err) => {
        if (!err) {
          updatePassword({
            id: localStorage.getItem('userId'),
            oldPassword: this.form.getFieldValue('oldPassword'),
            password: this.form.getFieldValue('password')
          }).then(res => {
            if (res.success) {
              message.success('修改密码成功')
              setTimeout(() => {
                localStorage.clear()
                this.$nextTick(() => {
                  window.location.reload()
                })
              }, 1000)
            } else {
              message.warning(res.detail)
            }
          })
        }
      })
    }
  }
}
</script>